package spring.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class DemoInterceptor extends HandlerInterceptorAdapter {
    private String startTimeKey = "startTime";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute(startTimeKey, startTime);
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (Long)request.getAttribute(startTimeKey);
        request.removeAttribute(startTimeKey);
        long endTime = System.currentTimeMillis();
        System.out.println("执行所花时间：" + (endTime - startTime));
        super.postHandle(request, response, handler, modelAndView);
    }
}
